<template>
    <view class="main">
        <nut-uploader :url="uploadUrl" v-model:file-list="defaultFileList" maximum="3" multiple
            :before-upload="beforeXhrUpload" @delete="deleteImg"></nut-uploader>
    </view>
</template>

<script setup>
import { ref } from 'vue';
import { BASE_URL } from '@/config/base'

const uploadUrl = ref('')
const defaultFileList = ref([])
const actionUrl = BASE_URL + "/prod-api/common/upload"
const imageList = ref([])
const emit = defineEmits(['upload'])
const beforeXhrUpload = (_UploadFile, options) => {
    console.log(options, 'oo')
    return new Promise((resolve, reject) => {
        defaultFileList.value.forEach(item => item.status = 'uploading')
        const url = options.filePath
        uni.uploadFile({
            url: actionUrl,
            filePath: url,
            name: 'file',
            header: {
                'content-type': 'multipart/form-data',
                'Authorization': 'Bearer ' + uni.getStorageSync("token")
            },
            success: (res) => {
                if (res.statusCode == 200) {
                    const data = JSON.parse(res.data)
                    defaultFileList.value.forEach(item => item.status = 'success')
                    imageList.value.push(data.url)
                    emit('upload', imageList.value.join(','))
                    resolve(imageList.value)
                } else {
                    defaultFileList.value.forEach(item => item.status = 'error')
                }

            },
            fail: (err) => {
                reject(err)
            },
        })
    })
}

const deleteImg = (data) => {
    console.log(data, 'dada')
    imageList.value.splice(data.index, 1)
    emit('upload', imageList.value.join(','))
}
</script>
<style lang="scss" scoped></style>